import { NextRequest, NextResponse } from 'next/server';
import { GloableResponseItem,  ResponseEnum } from '@/utils/request/res';
import { Auth, type ExtendedNextApiRequest, generateToken, hashPassword, LogOperation, ResponseHandler, verifyPassword, verifyToken } from '@/utils/decorator';
import prisma from '@/utils/db/PrismaService';

import { BaseController } from '@/utils/request/BaseController';
import { getCurrentTimeInShanghai } from '@/utils';
import { createDeptSchema } from '@/dbSchema/systemSchema';
import { GET as HttpGet, POST as HttpPost, PUT as HttpPut, DELETE as HttpDelete } from '@/utils/decorator';
import { createAllMethodHandlers } from '@/utils/request/routeRegistry';

class SystemDeptController extends BaseController {
    // 新增机构
    @Auth()
    @ResponseHandler()
    @HttpPost()
    @LogOperation({
        module: "机构管理",
        operationName: "新增机构"
    })
    static async addDept(request: ExtendedNextApiRequest) {
        const data = await request.customBody;
        data.create_time = getCurrentTimeInShanghai()
        data.update_time = getCurrentTimeInShanghai()
        if (!data.parent_id) {
            data.level = 1
        }
        if(data.level > data.max_level){
            return GloableResponseItem(ResponseEnum.fail, `机构等级最多不能超过${data.max_level}级`, null)
        }
        await createDeptSchema.parse(data);
        try {
            // 过滤掉数据库表中不存在的字段
            const { max_level, ...validData } = data;
            await prisma.sysDept.create({
                data: validData
            });
        } catch (error) {
            return GloableResponseItem(ResponseEnum.fail, "新增失败", null)
        }
        return GloableResponseItem(ResponseEnum.success, "新增成功", null)
    }

    // 获取机构列表
    @Auth()
    @ResponseHandler()
    @HttpGet()
    static async getDeptList(request: ExtendedNextApiRequest) {
        const data = await request.customBody;
        const departments = await prisma.sysDept.findMany();
        // 构建树形结构
        const buildTree = (nodes: any[], parent_id = 0): any[] => {
            return nodes
                .filter((node: any) => node.parent_id === parent_id)
                .map((node: any) => {
                    return {
                        title: node.dept_name,
                        key: node.id,
                        level: node.level,
                        height: 100, // 假设每个机构的高度为100
                        children: buildTree(nodes, node.id)
                    };
                });
        };
        return GloableResponseItem(ResponseEnum.success, "获取成功", buildTree(departments));
    }

    // 更新机构
    @Auth()
    @ResponseHandler()
    @HttpPut()
    @LogOperation({
        module: "机构管理",
        operationName: "更新机构"
    })
    static async updateDept(request: ExtendedNextApiRequest) {
        const data = request.customBody;
        await createDeptSchema.parse(data);
        await prisma.sysDept.update({
            where: { id: data.id },
            data
        });
        return GloableResponseItem(ResponseEnum.success, "修改成功", null)
    }

    // 删除机构
    @Auth()
    @ResponseHandler()
    @HttpDelete()
    @LogOperation({
        module: "机构管理",
        operationName: "删除机构"
    })
    static async deleteDept(request: ExtendedNextApiRequest) {
        const data = request.customBody;
        await prisma.sysDept.delete({
            where: { id: data.id }
        });
        return GloableResponseItem(ResponseEnum.success, "删除成功", null)
    }
            // // 如果机构下有老人，则不能删除
            // const elderly = await prisma.elderly.findMany({
            //     where: { dept_id: data.dept_id }
            // });
            // if (elderly.length > 0) {
            //     return GloableResponseItem(ResponseEnum.fail, "机构下有老人，不能删除", null);
            // }
            // // 如果机构下有用户，则不能删除
            // const user = await prisma.sysUser.findMany({
            //     where: { dept_id: data.dept_id }
            // });
            // if (user.length > 0) {
            //     return GloableResponseItem(ResponseEnum.fail, "机构下有用户，不能删除", null);
            // }

            // // 机构下有设备，不能删除
            // const device = await prisma.equipment.findMany({
            //     where: { dept_id: data.dept_id }
            // });
            // if (device.length > 0) {
            //     return GloableResponseItem(ResponseEnum.fail, "机构下有设备，不能删除", null);
            // }

            // // 事务
            // await prisma.$transaction(async (tx) => {
            //     // 如果是父机构，则删除所有子机构
            //     if (data.level == 1) {
            //         await tx.sysDept.deleteMany({
            //             where: { parent_id: data.dept_id }
            //         });
            //     }
            //     // 如果是子机构，则删除自身
            //     await tx.sysDept.delete({
            //         where: { ...data }
            //     });
    // });
}

// 使用自动路由处理器创建所有HTTP方法处理函数
const handlers = createAllMethodHandlers(SystemDeptController);

export const { GET, POST, PUT, DELETE } = handlers;